﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;

namespace Simulation.Framework
{
    public class ResManagerByResources : ManagerBehavior
    {
        private Dictionary<Type, Dictionary<string, Object>> cache = new Dictionary<Type, Dictionary<string, Object>>();

        #region override

        public override void Init()
        {
            cache = new Dictionary<Type, Dictionary<string, Object>>();
        }

        public override void Clear() {
            if (cache == null) return;
            foreach (var item in cache)
                item.Value.Clear();
            cache.Clear();
            cache = null;
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }

        public override void Restar() { }

        #endregion

        public T Load<T>(string fullName) where T : Object{
            Type type = typeof(T);
            if (!cache.ContainsKey(type))
                cache.Add(type,new Dictionary<string, Object>());
            Dictionary<string, Object> dic = cache[type];
            if (cache[type].ContainsKey(fullName))
                return cache[type][fullName] as T;
            T t = Resources.Load<T>(fullName);
            if(t != null)
                cache[type].Add(fullName, t);
             return t;
        }

        public void Remove<T>(string fullName)
        {
            Type type = typeof(T);
            if (!cache.ContainsKey(type) || !cache[type].ContainsKey(fullName))
                return;
            cache[type].Remove(fullName);
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }

        public void RemoveAll<T>() {
            Type type = typeof(T);
            if (cache.ContainsKey(type))
                cache[type].Clear();
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }
    }
}